package com.whjz.mpass;

import com.alibaba.fastjson.JSON;
import com.whjz.mpass.enums.DeliveryType;
import com.whjz.mpass.model.*;
import com.whjz.mpass.util.*;
import com.whjz.mpass.model.*;
import com.whjz.mpass.util.HttpClientUtil;
import com.whjz.mpass.util.SignUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author youkun
 * @data 2.18/7/6
 * mpass消息推送方法
 *
 */
public class MpassPushUtils {

    /**
     * 推送接口服务地址
     */
    private static String mpsAPIAddress = "https://cn-hangzhou-mps-api.cloud.alipay.com";

    /**
     * 应用标识
     */
    private static final String appId       = "B5B85AD200904";

    /**
     * 环境标识
     */
    private static final String workSpaceId   = "default";

    /**
     * 字符集设置
     */
    private static final String charSet     = "UTF-8";

    /**
     * RSA私钥，要求2048位的密钥对，接口调用前请现在mpaas控制台登记该RSA私钥对应的公钥
     * 公钥:
     * MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5+FT8wzzTo9PO8foVeJZKbwN7zbWyiFk13Ou3mHwzmvEIE1ZAQKQ7w77IsgAbpyVJWERamPiY+ORJIulsZudUjTQj9a6rT06P4+bh/aoB/yv6VtUIl8dtKoVpeCW4FZab+Q0mM5IQzwbABmIzAFxDtaYcXc9sLDXsU96THMUCP3bbjTARBZUB1+GoWlfMmoJsGwFTtqUHm4VXXPnJHInXLtJdhhsFpiHjjYDGIqDYDvLD3VAT+fDuor9mHytfKGEwpb1uvJqdRwx9VlzBnTMtPOefHLJG4ocA3e/5Uoo5BAsAUthg1pK4392sb3AxY6wQjZ3pijmX30/zzEqW/vMLQIDAQAB
     */
    private static final String rsaKey =
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDn4VPzDPNOj087" +
                    "x+hV4lkpvA3vNtbKIWTXc67eYfDOa8QgTVkBApDvDvsiyABunJUlYRFqY+Jj45Ek" +
                    "i6Wxm51SNNCP1rqtPTo/j5uH9qgH/K/pW1QiXx20qhWl4JbgVlpv5DSYzkhDPBsA" +
                    "GYjMAXEO1phxdz2wsNexT3pMcxQI/dtuNMBEFlQHX4ahaV8yagmwbAVO2pQebhVd" +
                    "c+ckcidcu0l2GGwWmIeONgMYioNgO8sPdUBP58O6iv2YfK18oYTClvW68mp1HDH1" +
                    "WXMGdMy08558cskbihwDd7/lSijkECwBS2GDWkrjf3axvcDFjrBCNnemKOZffT/P" +
                    "MSpb+8wtAgMBAAECggEAKy3+oAgNVtfA/XTggv2/dNIcFiu0G7fUO3rDWY4LdaUD" +
                    "xLAintmHe7zibzunOPHXpDpLL/Chu9AouxF2LXi49xH2tJJb+N6p9iQb5lm8OKCJ" +
                    "cX8cT7o+oeH6XgVQkz4BYUyxrrLbKgoLTR10J+ks0IKNqLN3vWtw/we50nqrhHDG" +
                    "lDSNa6MQfNARfuXs5IrVbQj2qduIHqqp6wuLawNG5gJWh0aWq3LWp9SJ2aaUYJkb" +
                    "MQMuIFvueobiZ6BKDpgsWUNvfLumogvVZ8VDESh0xIp1siH6Xyhwdi0Zr6/rV2v+" +
                    "Zb+5QSY7k+QLDNPuveM+ob/IwGHfJw0nSHF6PHjv0QKBgQD+d+fZqF2EzgD16SV9" +
                    "uZFh/U1wQjSxrVX5CzvHh3fPw/i+BkNVEqP6qH2w2/RRCiWOUrqSIMkhndgCn+HF" +
                    "4VvvmSOTFMkCVvCykMD/nOlFl4wULiN3pe9HOEay9K25CzyP3mSf86VXz/Ix/ABv" +
                    "v+E47d6mUC756b6/l0ICxF2m3wKBgQDpRp4WrtevQhWEkzDBHbqotZYn6UbxwCj2" +
                    "se0kmA4FLFOGSOBK6T3ByWBZ/nyP/l9+DmehcJuYU8wiBOIFwKXDHN6Ey6+ry43D" +
                    "nhmGKBuOOd13ahcBjmHdzQE5+zvL6BySHWcnkufzHaDswdfsjCODI7XTLaVa8ivz" +
                    "TidQ6t7qcwKBgQCXqLjapRiPdQNnjDuW8cju4LuNYzfqiQcLNaG8KkXC4uZVwn/Q" +
                    "rRpj4pV+majDv8tgRngBbV7SFTPPZKB3gfd8FgX4u9OM/GnZ0qHj9g2lN0v6HwFu" +
                    "Zsvz41tnfqIm/cZrbD0Gg3yQmFOdbLaJ448Ekeg3sOQ+eAwCPdDOu1+hewKBgCW+" +
                    "k13ANI3a93hYCI92q/kYSI90o1ICcZ5Y87H0GHCl123m5MO6MY/lcX2eO7Fgyzqu" +
                    "Qf5RJhvjkyf9+kRMA4Yqaaa6/lWhvfJk5mRaoPrGShtEQyyxSQyGWyhyih5YFCdg" +
                    "MoyorHcd2Cf2xWU015okcQsWW6b3gD0B7EKffioZAoGAWoydslAmOpIaylZsTo6r" +
                    "TEjaemmJluzy+NPV+bXJCppK6k6cpt12S/qiuSbhwwbiaNhLJvJiNDzINSjle8B4" +
                    "IAHIuvrJ6Gr+wupszT0M7fs/uxfeN/LiedLQg8sV6NFO2ZojPD8hWvZZmbfKDsak" +
                    "zd5fqM6rE3uhHk8IJXlCUGo=";

    /**
     *
     * @param pushBroadcastReq
     * @return
     * @throws Exception
     * 群发推送
     */
    public static HttpClientUtil.HttpInvokeResult pushBroadcast(PushBroadcastReq pushBroadcastReq ) throws Exception{
        if(pushBroadcastReq==null){
            throw new Exception("pushBroadcastReq is null");
        }
        String reqContent = JSON.toJSONString(pushBroadcastReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);
        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushbroadcast/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 批量推送
     * @param pushMultipleReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult pushMultiple(PushMultipleReq pushMultipleReq ) throws Exception{
        if(pushMultipleReq==null){
            throw new Exception("pushMultipleReq is null");
        }
        String reqContent = JSON.toJSONString(pushMultipleReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);
        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushmultiple/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return  HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 简单推送
     * @param pushSimpleReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult pushSimple(PushSimpleReq pushSimpleReq ) throws Exception{
        if(pushSimpleReq==null){
            throw new Exception("pushSimpleReq is null");
        }

        String reqContent = JSON.toJSONString(pushSimpleReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushsimple/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     *  模板推送
     * @param pushTemplateReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult pushTemplate(PushTemplateReq pushTemplateReq ) throws Exception{
        if(pushTemplateReq==null){
            throw new Exception("pushTemplateReq is null");
        }
        String reqContent = JSON.toJSONString(pushTemplateReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushtemplate/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 手机绑定
     * @param bindAppReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult  bindApp(BindAppReq bindAppReq) throws Exception{
        if(bindAppReq==null){
            throw new Exception("bindAppReq is null");
        }
        String reqContent = JSON.toJSONString(bindAppReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/bind/bind/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 手机解绑
     * @param unbindAppReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult  unbindApp(UnbindAppReq unbindAppReq) throws Exception{
        if(unbindAppReq==null){
            throw new Exception("unbindAppReq is null");
        }
        String reqContent = JSON.toJSONString(unbindAppReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/bind/unbind/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }


    /**
     * 设备上报 ios 推送需要上报
     * @param reportAppReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult  reportApp(ReportAppReq reportAppReq) throws Exception{
        if(reportAppReq==null){
            throw new Exception("reportAppReq is null");
        }
        String reqContent = JSON.toJSONString(reportAppReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/deviceinfo/report/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }


    public static void main(String... args){
        boolean force = true;
        int mode = 4;

        if (force || mode == 1) {
            //群发推送
            PushBroadcastReq pushBroadcastReq = new PushBroadcastReq();
            pushBroadcastReq.setTaskName("群发推送");
            //群发只有两种模式，针对安卓设备或者针对IOS设备
            pushBroadcastReq.setDeliveryType(DeliveryType.DEVICE_IOS.getValue());
            pushBroadcastReq.setExpiredSeconds(600);

            //请根据实际的模版名称进行设置
            pushBroadcastReq.setTemplateName("push1");

            //模版中配置的变量值，请根据实际模版中的变量进行设置
            Map<String,String> templateKV = new HashMap<String, String>();
            templateKV.put("title", "title-");
            templateKV.put("content", "content-");
            pushBroadcastReq.setTemplatekv(templateKV);

            Map<String,String> extendedParam = new HashMap<String, String>();
            extendedParam.put("test","自定义扩展参数");
            pushBroadcastReq.setExtended_params(extendedParam);

            pushBroadcastReq.setMsgkey(String.valueOf(System.currentTimeMillis()));
            try {
                HttpClientUtil.HttpInvokeResult result = MpassPushUtils.pushBroadcast(pushBroadcastReq);
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (force || mode == 2) {
            //批量推送
            PushMultipleReq pushMultipleReq = new PushMultipleReq();
            pushMultipleReq.setTaskName("批量推送");
            pushMultipleReq.setDeliveryType(DeliveryType.USER.getValue());
            pushMultipleReq.setExpiredSeconds(600);

            //请根据实际的模版名称进行设置
            pushMultipleReq.setTemplateName("push2");

            Map<String,TargetMsgInfo> targetMsgInfoMap = new HashMap<String, TargetMsgInfo>(2);

            TargetMsgInfo targetMsgInfo1 = new TargetMsgInfo();
            //模版中配置的变量值，请根据实际模版中的变量进行设置
            Map<String,String> templateKVv = new HashMap<String, String>();
            templateKVv.put("title", "title-");
            templateKVv.put("content", "content-");
            targetMsgInfo1.setTemplatekv(templateKVv);
            targetMsgInfo1.setMsgkey(String.valueOf(System.currentTimeMillis()));
            //请根据实际的设备标识或者用户标识进行替换
            targetMsgInfoMap.put("0050",targetMsgInfo1);

            TargetMsgInfo targetMsgInfo2 = new TargetMsgInfo();
            //模版中配置的变量值，请根据实际模版中的变量进行设置
            Map<String,String> templateKV2 = new HashMap<String, String>();
            templateKV2.put("title", "title-2");
            templateKV2.put("content", "content-2");
            targetMsgInfo2.setTemplatekv(templateKV2);
            targetMsgInfo2.setMsgkey(String.valueOf(System.currentTimeMillis())+"121");
            //请根据实际的设备标识或者用户标识进行替换
            targetMsgInfoMap.put("1fe792f00163100080a730300a19467b",targetMsgInfo2);
            pushMultipleReq.setTarget_msginfo(targetMsgInfoMap);


            Map<String,String> extendedParams = new HashMap<String, String>();
            extendedParams.put("test","自定义扩展参数");
            pushMultipleReq.setExtended_params(extendedParams);
            try {
                HttpClientUtil.HttpInvokeResult result = MpassPushUtils.pushMultiple(pushMultipleReq);
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (force || mode == 3) {
            //简单推送
            PushSimpleReq pushSimpleReq = new PushSimpleReq();
            pushSimpleReq.setTaskName("简单推送");
            pushSimpleReq.setContent("简单推送-内容");
            pushSimpleReq.setTitle("简单推送-标题");
            pushSimpleReq.setUri("http://127.0.0.1");
            pushSimpleReq.setDeliveryType(DeliveryType.USER.getValue());
            pushSimpleReq.setExpiredSeconds(600);

            Map<String,String> extendedParamss = new HashMap<String, String>();
            extendedParamss.put("test","自定义扩展参数");
            pushSimpleReq.setExtended_params(extendedParamss);

            Map<String,String> target = new HashMap<String, String>();
            String msgKey = String.valueOf(System.currentTimeMillis());
            target.put("0050",msgKey);
            pushSimpleReq.setTarget_msgkey(target);
            try {
                HttpClientUtil.HttpInvokeResult result = MpassPushUtils.pushSimple(pushSimpleReq);
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (force || mode == 4) {
            //模板推送
            PushTemplateReq pushTemplateReq = new PushTemplateReq();
            pushTemplateReq.setTaskName("模板推送");
            pushTemplateReq.setDeliveryType(DeliveryType.USER.getValue());
            pushTemplateReq.setExpiredSeconds(600);

            //请根据实际的模版名称进行设置
            pushTemplateReq.setTemplateName("push4");

            //模版中配置的变量值，请根据实际模版中的变量进行设置
            Map<String,String> templateKVw = new HashMap<String, String>();
            templateKVw.put("title", "title-");
            templateKVw.put("content", "content-");
            pushTemplateReq.setTemplatekv(templateKVw);

            Map<String,String> extendedParamsss = new HashMap<String, String>();
            extendedParamsss.put("test","自定义扩展参数");
            pushTemplateReq.setExtended_params(extendedParamsss);

            Map<String,String> targetsss = new HashMap<String, String>();
            String msgKeyss = String.valueOf(System.currentTimeMillis());
            targetsss.put("0050",msgKeyss);
            pushTemplateReq.setTarget_msgkey(targetsss);
            try {
                HttpClientUtil.HttpInvokeResult result = MpassPushUtils.pushTemplate(pushTemplateReq);
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
